package com.fyyg.service.user;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.fyyg.common.code.Code;
import com.fyyg.common.code.GetEContent;
import com.fyyg.common.page.PageParam;
import com.fyyg.common.util.DesUtilsApps;
import com.fyyg.common.util.MD5;
import com.fyyg.common.util.SafetyUtils;
import com.fyyg.common.util.ShardingMonthUtil;
import com.fyyg.common.util.date.YXDate;
import com.fyyg.concurrent.AccountLock;
import com.fyyg.dal.bbs.TBusiBbsUserMapper;
import com.fyyg.dal.shop.TBusiShopCouponMemberMapper;
import com.fyyg.dal.shop.TBusiShopProductBatchAdditionalGroupMapper;
import com.fyyg.dal.shop.TBusiShopProductMapper;
import com.fyyg.dal.system.TBusiConfigurationMapper;
import com.fyyg.dal.user.TBusiCreditIntegralControlMapper;
import com.fyyg.dal.user.TBusiCreditIntegralLogMapper;
import com.fyyg.dal.user.TBusiFudouPotMemberMapper;
import com.fyyg.dal.user.TBusiMemberAccountLogMapper;
import com.fyyg.dal.user.TBusiMemberAccountReviewMapper;
import com.fyyg.dal.user.TBusiMemberAddressMapper;
import com.fyyg.dal.user.TBusiMemberGoRealOrderMapper;
import com.fyyg.dal.user.TBusiMemberGoRecordMapper;
import com.fyyg.dal.user.TBusiMemberGoVirtualOrderMapper;
import com.fyyg.dal.user.TBusiMemberLoginlogMapper;
import com.fyyg.dal.user.TBusiMemberMapper;
import com.fyyg.dal.user.TBusiMemberRechargeMapper;
import com.fyyg.dal.user.TBusiMemberTrackingMapper;
import com.fyyg.dal.user.TBusiMobileCodeMapper;
import com.fyyg.interfaces.user.TBusiMemberService;
import com.github.pagehelper.StringUtil;

/**
 * @author PengYu
 * @date 2016年3月21日 下午4:40:19
 */
@Service("busiMemberService")
public class TBusiMemberServceImpl implements TBusiMemberService {
	private final static Logger logger = LogManager.getLogger(TBusiMemberServceImpl.class);

	@Autowired
	private TBusiMemberMapper tBusiMemberMapper;
	@Autowired
	private TBusiMobileCodeMapper tBusiMobileCodeMapper;
	@Autowired
	private TBusiMemberLoginlogMapper tBusiMemberLoginLogMapper;
	@Autowired
	private TBusiFudouPotMemberMapper tBusiFudouPotMemberMapper;
	
	@Autowired
	TBusiShopCouponMemberMapper tBusiShopCouponMemberMapper;
	@Autowired
	private TBusiBbsUserMapper  tBusiBbsUserMapper;
    @Autowired
    TBusiMemberAccountLogMapper accountLogMapper;
    @Autowired
    private TBusiMemberMapper userServiveMapper;
    @Autowired
    private TBusiMemberGoVirtualOrderMapper memberGoVirtualOrderMapper;
    @Autowired
    private TBusiMemberGoRecordMapper memberGoRecordMapper;
    @Autowired
    private TBusiShopProductBatchAdditionalGroupMapper  productBatchAdditionalGroupMapper;
    @Autowired
    private TBusiShopProductMapper shopProductMapper;
    @Autowired
    private TBusiMemberAccountReviewMapper reviewMapper;
    @Autowired
    private TBusiMemberRechargeMapper rechargeMapper;
    
    @Autowired
    private TBusiMemberAddressMapper memberAddressMapper;
    @Autowired
    private TBusiMemberGoRealOrderMapper memberGoRealOrderMapper;
                                                              
    @Autowired     
	private TBusiCreditIntegralLogMapper tBusiCreditIntegralLogMapper;
    
    @Autowired
	private TBusiCreditIntegralControlMapper tBusiCreditIntegralControlMapper;
    @Autowired
    private TBusiConfigurationMapper  tBusiConfigurationMapper;
    @Autowired
    private TBusiMemberTrackingMapper tBusiMemberTrackingMapper;
    
	@Override
	public int findMemberByMobile(String mobile) {
		int count= tBusiMemberMapper.selectMemberByMobile(mobile);
		return count;
	}

	@Override
	public int insertMobileCode(Map map) {
		int IPCount = tBusiMobileCodeMapper.selectMobileCodeCountByIP(map.get("MOBILE").toString(),map.get("ADDIP").toString());
		if(IPCount>30){
			System.out.println("---------------------同一ip短信发送大于30条:"+map.get("ADDIP").toString());
			return -1;
		}
		int registrCount = tBusiMobileCodeMapper.selectMobileCodeCountByDate(map.get("MOBILE").toString());
		if(registrCount>10){
			System.out.println("---------------------当日注册短信发送大于10条:"+map.get("MOBILE").toString());
			return -1;
		}
		int oneminutebefreCount = tBusiMobileCodeMapper.selectMobileCodeCountByOneMinutebefore(map.get("MOBILE").toString());
		if(oneminutebefreCount>0){
			System.out.println("---------------------短信发送频率快过1分钟:"+map.get("MOBILE").toString());
			return -1;
		}
		int number= tBusiMobileCodeMapper.insertMobileCode(map);
		return number;
	}
	
	
	@Override
	public int clearMessage() {
		int count = tBusiMobileCodeMapper.deleteMobileCodeInvalid();		
		return count;
	}
	
	@Override
	public TBusiMember selectByPrimaryKey(Integer uid){
		return userServiveMapper.selectByPrimaryKey(uid);
	}
 
	@Override
	public int findByMobileAndCode(String mobile, String code) {
		int count =tBusiMobileCodeMapper.findByMobileAndCode(mobile, code);
		return count;
	}

	@Override
	public String register(String smsMob,String password,int regPlat,String code,String ip,int inviter,int dInviter,
			String headImg,String QQId,String WBId,String WXiD){
		//随机1-16
		int i=(int)(1+Math.random()*(16-1+1));
		
		TBusiMember user= new TBusiMember();
		user.setIsReal(0);
		user.setIsEmail(0);
		user.setUserName(smsMob);//用户名默认为手机号码
		user.setNickName(smsMob);
		user.setIsMobile(1);
		user.setMobile(smsMob);
		user.setPassword(StringUtil.isEmpty(password)? MD5.enCode("123456"):MD5.enCode(password));
		user.setCashPassword(null);//默认为null
		user.setRegIp(ip);
		user.setGroupId(0);
		user.setPassCode("-1");
		user.setEmailCode("-1");
		user.setHeadImg( StringUtil.isEmpty(headImg) ? "/res/images/headimage/"+i+".jpg" : headImg);
		user.setMoney(new BigDecimal(0));
		user.setFudou(new BigDecimal(0));
		user.setBounty(new BigDecimal(0));
		user.setRedpacket(new BigDecimal(0));
		user.setMobileCode(code);
		user.setScore(0);
		user.setRegKey("");
		user.setExperience(0);
		user.setRegTime(YXDate.getTime());
		user.setLoginTimes(1);//注册成功后直接登录，登录次数为1
		user.setRegPlat(regPlat);
		user.setAutoUser(9);
		user.setInviter(inviter);
		user.setuStatus(0);
		user.setdInviter(dInviter);
		user.setIsDaren(0);
		user.setuType(0);
		user.setFatherUid(0);
		user.setLogins(0);
		user.setQqId(StringUtil.isEmpty(QQId) ? "" : QQId);
		user.setWeiboId(StringUtil.isEmpty(WBId) ? "" : WBId);
		user.setWeixinId(StringUtil.isEmpty(WXiD) ? "" : WXiD);
		
		StringBuffer sb=new StringBuffer();
		sb.append(smsMob);
	    sb.append(YXDate.getTime()); 
		String oc;
		try {
			 oc = DesUtilsApps.encryptDES(sb.toString(),DesUtilsApps.keys);
			 user.setOnlycode(oc);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		if(tBusiMemberMapper.insert(user)>0){
//			TBusiMember member =tBusiMemberMapper.selectMemberByPhone(smsMob);
//			//初始化bbs_user
//			TBusiBbsUser bbs=new TBusiBbsUser();
//			bbs.setUserId(member.getUid());
//			bbs.setNickName(smsMob);
//			bbs.setPoint(0);
//			bbs.setHeadImg(StringUtil.isEmpty(headImg) ? "res/images/headimage/"+i+".jpg" : headImg);
//			bbs.setPostCount(0);
//			bbs.setSeriesSignDay(0);
//			bbs.setRotateTimes(0);
//			bbs.setForbid(0);
//			bbs.setSettingImage(null);
//			if(tBusiBbsUserMapper.insert(bbs)>0){
//				logger.info("论坛用户初始化成功");
//			}else{
//				logger.error("论坛用户初始化失败");
//			}
			try {
				Thread.sleep(800);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return SafetyUtils.createSimpleReturn(Code.SUCCESS,GetEContent.getEContent(Code.SUCCESS));
		}
		return SafetyUtils.createSimpleReturn(Code.ERROR_NORMAL, GetEContent.getEContent(Code.ERROR_NORMAL));
	}
	


	/**
	 * 登录核心
	 */
	@Override
	public String login(String username,String password,String loginType) {
		logger.info(username+"login-----------登录验证----------");
		if(username==null || username.trim().equals("")){
			return SafetyUtils.createSimpleReturn(Code.LOGIN_USER_NULL, GetEContent.getEContent(Code.LOGIN_USER_NULL));
		} 
		if(password==null || password.trim().equals("")){
			return SafetyUtils.createSimpleReturn(Code.LOGIN_PASSWORD_NULL, GetEContent.getEContent(Code.LOGIN_PASSWORD_NULL));
		}
		if(loginType==null || loginType.trim().equals("")){
			return SafetyUtils.createSimpleReturn(Code.ERROR_PARAMS, GetEContent.getEContent(Code.ERROR_PARAMS));
		}		

		TBusiMember user = selectByNameOrPhone(username);
		if (user == null) {//用户名不存在
			return SafetyUtils.createSimpleReturn(Code.LOGIN_ERROR, GetEContent.getEContent(Code.LOGIN_ERROR));
		}
		if(user.getuStatus()==2 || user.getuStatus()==8){ //状态冻结或锁
			if(user.getLogins()==6){ //当天连续输入错误数6次冻结
				return SafetyUtils.createSimpleReturn(Code.ERROR_VERIFY, "账号连续输入密码错误已达上限，可通过绑定手机找回!");
			}
			return SafetyUtils.createSimpleReturn(Code.MEMBER_STATUS_DONGJIE, GetEContent.getEContent(Code.MEMBER_STATUS_DONGJIE));
		}
		if(user.getuStatus()==9){ //状态已删除
			return SafetyUtils.createSimpleReturn(Code.MEMBER_STATUS_DELETE, GetEContent.getEContent(Code.MEMBER_STATUS_DELETE));
		}
		if(user.getLogins()>=6){
			logger.info(username+"登录密码错误---------------满了6次");
			tBusiMemberMapper.updateMemberSetLogins(user.getLogins(),user.getUid());
			return SafetyUtils.createSimpleReturn(Code.ERROR_VERIFY, "账号连续输入密码错误已达上限，可通过绑定手机找回!");
		}
		
		int ls=0;
		if(Integer.valueOf(loginType)==0 || Integer.valueOf(loginType)==1){
			if (!user.getPassword().equals(MD5.enCode(password))) {//PC登录密码错误
				ls=1;
				//return SafetyUtils.createSimpleReturn(Code.LOGIN_ERROR, GetEContent.getEContent(Code.LOGIN_ERROR));
			} 
		}else{
			if (!user.getPassword().equals(MD5.enCode(password))) {//APP登录密码错误
				ls=1;
				//return SafetyUtils.createSimpleReturn(Code.LOGIN_ERROR, GetEContent.getEContent(Code.LOGIN_ERROR));
			} 
		}
		if(ls==1){ //密码错误logins+1，第6次输入错误上限
			logger.info(username+"登录密码错误---------------logins+1");
			user.setLogins(user.getLogins()+1);
			if(user.getLogins()>=6){
				logger.info(username+"登录密码错误---------------满了6次");
				tBusiMemberMapper.updateMemberSetLogins(user.getLogins(),user.getUid());
				return SafetyUtils.createSimpleReturn(Code.ERROR_VERIFY, "连续输入密码错误已达上限，可通过绑定手机找回!");
			}else{
				tBusiMemberMapper.updateMemberSetLogins(user.getLogins(),user.getUid());
				int n=6-user.getLogins();
				if(n<3){
					return SafetyUtils.createSimpleReturn(Code.ERROR_VERIFY, "您还可以输入"+n+"次，忘记了密码可通过绑定手机找回!");
				}else{
					return SafetyUtils.createSimpleReturn(Code.ERROR_VERIFY, "用户名或密码输入有误");
				}
			}
		}else{
			user.setLogins(0);
			tBusiMemberMapper.updateMemberSetLogins(user.getLogins(),user.getUid());
		}
		//验证成功
		return SafetyUtils.createBeanReturn(Code.LOGIN_SUCCESS, GetEContent.getEContent(Code.LOGIN_SUCCESS),user);
	}
	
	/**
	 * 支持2种登陆方式（用户名，手机）
	 * @author PengYu
	 * @date 2016年3月24日 下午3:20:43
	 */
	public TBusiMember selectByNameOrPhone(String userName) {
		// 1 、判断用户名登陆，根据用户名查询用户信息
		TBusiMember user=tBusiMemberMapper.selectMemberByUserName(userName);
		// 2 、用户名查询为空，判断手机号登陆，需认证通过
		if (user==null){
			user = tBusiMemberMapper.selectMemberByPhone(userName);
		}
		return user;
	}

	
	

	@Override
	public int findByMobileCodeTimeOut(String mobile, String code) {
		return tBusiMobileCodeMapper.findByMobileCodeTimeOut(mobile, code);
	}

	@Override
	public int updateMember(TBusiMember tbm) {
		return 	tBusiMemberMapper.updateByPrimaryKeySelective(tbm);
	}

	@Override
	public TBusiMember selectMemberByUserName(String username) {
		return tBusiMemberMapper.selectMemberByUserName(username);
	}

	

	@Override
	public TBusiMobileCode mobileCodeModle(String mobile, String code) {
		return tBusiMobileCodeMapper.mobileCodeModle(mobile, code);
	}

	@Override
	public int updateMobileCodeUseCode(String mobile, String code) {
		return tBusiMobileCodeMapper.updateMobileCodeUseCode(mobile, code);
	}

	@Override
	public int selectUseCodeByMobile(String mobile) {
		return tBusiMobileCodeMapper.selectUseCodeByMobile(mobile);
	}
	
	@Override
	public TBusiMember selectMemberByPhone(String phone) {
		return tBusiMemberMapper.selectMemberByPhone(phone);
	}
	
	@Transactional(rollbackFor = RuntimeException.class)
	public boolean setOrderAddress(String addressId,Integer uid,String recordId){
		 TBusiMember tbm=tBusiMemberMapper.findTBusiMemberByUid(uid);
		 try {
			 synchronized (AccountLock.lockMember(tbm.getUid())){
					TBusiMemberAddress address =memberAddressMapper.selectMemberAddressModelByIdUid(Integer.parseInt(addressId), uid);
					if(null!=address){
						TBusiMemberGoRecord gorecord=memberGoRecordMapper.selectGoRecordIdUid(Integer.parseInt(recordId), uid);				
						gorecord.setConfirmStatus(1);
						gorecord.setConfirmaddrTime(YXDate.getTime());
						// 添加地址
						TBusiMemberGoRealOrder realOrder = memberGoRealOrderMapper.selectGorealOrderByRecordId(String.valueOf(gorecord.getId()));
						if(null!=realOrder){
							realOrder.setDeliveryHire(0L);
							realOrder.setReceiveName(address.getReceiver());
							realOrder.setReceivePhone(address.getMobile());
							realOrder.setConfirmaddrTime(YXDate.getTime());
							realOrder.setReceiveAddress(address.getProvince()+address.getCity()+address.getDistrict()+address.getStreet());
							realOrder.setStatus(0);
							realOrder.setProductType(gorecord.getProductType());
							int realOrderNum=0;
							int gorecordNum=0;
							realOrderNum=memberGoRealOrderMapper.updateByPrimaryKeySelective(realOrder);
							gorecordNum=memberGoRecordMapper.updateByPrimaryKeySelective(gorecord);
							if(realOrderNum>0&&gorecordNum>0){
								return true;
							}else{
								return false;
							}
						}
					}
				 }
		} catch (Exception e) {
			// TODO: handle exception
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw new RuntimeException(e.getMessage());
		}
		
		 return false;
	}

	@Transactional(rollbackFor = RuntimeException.class)
	public String updateMemberLogPwd(TBusiMember user,String code,String password,String password2,String type){
		TBusiMember tbm = tBusiMemberMapper.findTBusiMemberByUid(user.getUid());
		try {
			synchronized (AccountLock.lockMember(tbm.getUid())) {
				int numb = selectUseCodeByMobile(user.getMobile());
				if (numb == 0) {
					if (StringUtils.isBlank(code)) {
						return SafetyUtils.createSimpleReturn(Code.MESSAGE_CODE_NULL,GetEContent.getEContent(Code.MESSAGE_CODE_NULL));
					}
					// 验证CODE
					int smc = findByMobileAndCode(user.getMobile(), code);
					if (smc == 0) {
						return SafetyUtils.createSimpleReturn(Code.MESSAGE_CODE_ERROR, GetEContent.getEContent(Code.MESSAGE_CODE_ERROR));
					}
					// 判断验证码是否过期 30分钟内
					int count = findByMobileCodeTimeOut(user.getMobile(), code);
					if (count == 0) {
						return SafetyUtils.createSimpleReturn(Code.MESSAGE_CODE_TIMEOUT,GetEContent.getEContent(Code.MESSAGE_CODE_TIMEOUT));
					}
					// 修改验证成功
					updateMobileCodeUseCode(user.getMobile(), code);
				}

				if (StringUtils.isBlank(password)) {
					return SafetyUtils.createSimpleReturn(Code.PASSWORD_NULL,GetEContent.getEContent(Code.PASSWORD_NULL));
				}
				if (!password2.equals(password)) {
					return SafetyUtils.createSimpleReturn(Code.PASSWORD_FALSE,GetEContent.getEContent(Code.PASSWORD_FALSE));
				}
				if(type.equals("1")){
					// 修改的密码跟原密码一致
					if (MD5.enCode(password).equals(user.getPassword())) {
						return SafetyUtils.createSimpleReturn(Code.PASSWORD_UNMODIFIED,GetEContent.getEContent(Code.PASSWORD_UNMODIFIED));
					}
				}
				if(type.equals("2")){
					//修改的密码跟原密码一致
					if(MD5.enCode(password).equals(user.getCashPassword())){
						return SafetyUtils.createSimpleReturn(Code.PASSWORD_UNMODIFIED, GetEContent.getEContent(Code.PASSWORD_UNMODIFIED));
					}
					//判断是否为6位数字密码
					if(password.length()!=6){
						 return SafetyUtils.createSimpleReturn(Code.PAY_PASSWORD_ERROR, GetEContent.getEContent(Code.PAY_PASSWORD_ERROR));
					}
					for (int i = 0; i < password.length(); i++){
						//System.out.println(password.charAt(i));
						if (!Character.isDigit(password.charAt(i))){
							//有不为数字的返回
						    return SafetyUtils.createSimpleReturn(Code.PAY_PASSWORD_ERROR, GetEContent.getEContent(Code.PAY_PASSWORD_ERROR));
						}
					}
					
				}
				if(type.equals("1")){
					user.setPassword(MD5.enCode(password));
					if (tBusiMemberMapper.updateByPrimaryKeySelective(user) > 0) {
						return SafetyUtils.createSimpleReturn(Code.SUCCESS,GetEContent.getEContent(Code.SUCCESS));
					} else {
						return SafetyUtils.createSimpleReturn(Code.ERROR_NORMAL,GetEContent.getEContent(Code.ERROR_NORMAL));
					}
				}
				if(type.equals("2")){
					user.setCashPassword(MD5.enCode(password));
					if(tBusiMemberMapper.updateByPrimaryKeySelective(user)>0){
						return SafetyUtils.createSimpleReturn(Code.SUCCESS, GetEContent.getEContent(Code.SUCCESS));
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw new RuntimeException(e.getMessage());
		}
		return SafetyUtils.createSimpleReturn(Code.ERROR_NORMAL, GetEContent.getEContent(Code.ERROR_NORMAL));
	}
	
	@Transactional(rollbackFor = RuntimeException.class)
	public String updateUserName(TBusiMember user,String loginName){
		TBusiMember tbm = tBusiMemberMapper.findTBusiMemberByUid(user.getUid());
		try {
			synchronized (AccountLock.lockMember(tbm.getUid())) {
				if (StringUtils.isBlank(loginName)) {
					return SafetyUtils.createSimpleReturn(Code.USER_NULL,
							GetEContent.getEContent(Code.PASSWORD_NULL));
				}
				user.setUserName(loginName);
				if (updateMember(user) > 0) {
					// session.removeAttribute("loginUser");
					return SafetyUtils.createSimpleReturn(Code.SUCCESS,
							GetEContent.getEContent(Code.SUCCESS));
				} else {
					return SafetyUtils.createSimpleReturn(Code.ERROR_NORMAL,
							GetEContent.getEContent(Code.ERROR_NORMAL));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public String userVerifyAddress(TBusiMember user,String recordId ){
		try {
			if(StringUtil.isEmpty(recordId)){
				return SafetyUtils.createSimpleReturn("-1","参数错误");
			}
			TBusiMemberGoRecord gorecord = memberGoRecordMapper.selectGoRecordIdUid(Integer.parseInt(recordId),user.getUid());
			if(null!=gorecord){
				gorecord.setStatus(3);
				gorecord.setConfirmTime(YXDate.getTime());
				int result = memberGoRecordMapper.updateByPrimaryKeySelective(gorecord);
				if(result>0){
					return SafetyUtils.createSimpleReturn("0", "确认成功");
				}
			}else{
				return SafetyUtils.createSimpleReturn("-1","没有找到订单");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return SafetyUtils.createSimpleReturn("-1", "确认失败");
		}
		return SafetyUtils.createSimpleReturn("-1", "确认失败");
	}
	
	
	
	@Override
	public TBusiMember selectMemberByWXId(String wx_id) {
		return tBusiMemberMapper.selectMemberByWXId(wx_id);
	}

	
	
	@Override
	public Integer selectMobileCodeCountByDate(String mobile) {
		return tBusiMobileCodeMapper.selectMobileCodeCountByDate(mobile);
	}
	
	@Override
	public Integer selectMobileCodeCountByOneMinutebefore(String mobile) {
		return tBusiMobileCodeMapper.selectMobileCodeCountByOneMinutebefore(mobile);
	}

	

	@Transactional(rollbackFor = RuntimeException.class)
	public boolean updateMemberIntegral(Integer uid, Integer integralNumber,
			Integer addType) {
		synchronized (AccountLock.lockMember(uid)) {
			try {
				TBusiMember member = tBusiMemberMapper
						.findTBusiMemberByUid(uid);
				if (member == null) {
					String msg = "用户ID为:" + uid + "的用户不存在";
					logger.error(msg);
					throw new RuntimeException(msg);
				}
				// 用户原有积分
				Integer oldIntegeral = member.getIntegral();// 用户原有积分
				Integer newIntegeral = 0;// 用户新积分
				String integralMsg = "";// 积分变动描述
				Integer changeType = 1;// 改变类型 0支出 1收入
				// 1.晒单 送积分2.邀请注册 送积分3.绑定微信，微博，QQ 送积分4.消费 送积分5积分兑换'
				Integer changeIntegeral = 0;// 变动的积分
				double shMoney=0;//兑换的福豆数
				switch (addType) {
				case 1:
					//线程异常控制 防止重复送分
					PageParam<Map<String, Object>> pageParamSd=new PageParam<>();
					Map<String, Object> paramSd=new HashMap<>();
					paramSd.put("userId", uid);
					paramSd.put("addType", "1");
					paramSd.put("groupId", integralNumber);
					pageParamSd.setP(paramSd);
					List<Map<String, Object>> pageDataSd=tBusiCreditIntegralLogMapper.selectIntegralLogModel(pageParamSd);
					if(pageDataSd!=null && pageDataSd.size()>0)
					{
						//该用户已赠送过积分  该订单晒单已经赠送过积分了
						return false;
					}
					changeIntegeral = returnIntegralBycontrol(addType);
					if (changeIntegeral == 0) {
						return false;// 活动已锁定
					}
					integralMsg = "晒单,赠送" + changeIntegeral + "积分";
					newIntegeral = oldIntegeral + changeIntegeral;
					break; 
				case 2:
					changeIntegeral = returnIntegralBycontrol(addType);
					if (changeIntegeral == 0) {
						return false;// 活动已锁定
					}
					integralMsg = "邀请注册,赠送" + changeIntegeral + "积分";
					newIntegeral = oldIntegeral + changeIntegeral;
					break;
				case 3:
					changeIntegeral = returnIntegralBycontrol(addType);
					if (changeIntegeral == 0) {
						return false;// 活动已锁定
					}
					integralMsg = "绑定微信，微博，QQ,赠送" + changeIntegeral + "积分";
					newIntegeral = oldIntegeral + changeIntegeral;
					break;
				case 4://消费控制 
					/*changeIntegeral = returnIntegralBycontrol(addType);
					if (changeIntegeral == 0) {
						return false;// 活动已锁定
					}*/
					integralMsg = "下单消费,赠送" + integralNumber + "积分";
					newIntegeral = oldIntegeral + integralNumber;
					break;
				case 5:
					integralMsg = "积分兑换,消费" + integralNumber + "积分";
					if (oldIntegeral < integralNumber) {
						String msg = "用户ID为:" + uid + "的用户积分不足";
						logger.error(msg);
						throw new RuntimeException(msg);
					}
					changeType = 0;
					newIntegeral = oldIntegeral - integralNumber;
					changeIntegeral=integralNumber;
					// 兌换比例 控制兌换的金额  金额变动日志记录
					logger.info("插入资金流水【充值】日志start....");
					Integer cIntegral=returnIntegralBycontrol(addType);
					if(cIntegral==0)
					{
						return false;
					}
					shMoney=integralNumber/cIntegral;
					if(shMoney==0)
					{
						return false;
					}
					TBusiMemberAccountLog accountLog = new TBusiMemberAccountLog();
					accountLog.setUid(member.getUid());
					accountLog.setType(7);//兌换福豆
					Double money = member.getMoney().doubleValue() + shMoney;
					accountLog.setUseMoney(new BigDecimal(money));//(充值后)可用余额
					accountLog.setMoney(new BigDecimal(shMoney));//操作金额
					accountLog.setContent("积分兑换福豆");
					accountLog.setAddTime(YXDate.getTime());
					accountLog.setUserName(member.getUserName());
					accountLog.setAutoUser(member.getAutoUser());
					accountLog.setuType(member.getuType());
					accountLog.setShardingKey(ShardingMonthUtil.currentShardingMonth());
					int result  =  accountLogMapper.insert(accountLog);
					if(result <= 0 ){
						//插入资金充值日志失败
						String msg = "插入资金流水【充值】日志失败";
						logger.error(msg);
						throw new RuntimeException(msg);
					}else
					{
						member.setMoney(new BigDecimal(money));
					}
					break;
				case 6:
					//线程异常控制 防止重复送分
					PageParam<Map<String, Object>> pageParam=new PageParam<>();
					Map<String, Object> param=new HashMap<>();
					param.put("userId", uid);
					param.put("addType", "6");
					pageParam.setP(param);
					List<Map<String, Object>> pageData=tBusiCreditIntegralLogMapper.selectIntegralLogModel(pageParam);
					if(pageData!=null && pageData.size()>0)
					{
						//该用户已赠送过积分
						return false;
					}
					changeIntegeral = returnIntegralBycontrol(addType);
					if (changeIntegeral == 0) {
						return false;// 活动已锁定
					}
					integralMsg = "APP下载,赠送" + changeIntegeral + "积分";
					newIntegeral = oldIntegeral + changeIntegeral;
					break; 
				default:
					break;
				}
				// 添加积分日志
				TBusiCreditIntegralLog tBusiCreditIntegralLog = new TBusiCreditIntegralLog();
				tBusiCreditIntegralLog.setUserId(uid);
				tBusiCreditIntegralLog.setAddTime(YXDate.getTime());
				tBusiCreditIntegralLog.setAddType(addType);
				tBusiCreditIntegralLog.setChangeType(changeType);
				tBusiCreditIntegralLog.setDesc(integralMsg);
				tBusiCreditIntegralLog.setNumber(changeIntegeral);
				if(addType==1)
				{
					//如果是晒单  添加一列 groupId
					tBusiCreditIntegralLog.setGroupId(integralNumber);
				}
				if(addType==5)
				{
					//兑换  
					tBusiCreditIntegralLog.setFudouMoney((int)shMoney);
				}
				int result = tBusiCreditIntegralLogMapper
						.insert(tBusiCreditIntegralLog);
				if (result <= 0) {
					String msg = "积分日志记录失败";
					logger.error(msg);
					throw new RuntimeException(msg);
				}
				// 修改用户的积分账户
				member.setIntegral(newIntegeral);
				result = tBusiMemberMapper.updateByPrimaryKeySelective(member);
				if (result <= 0) {
					String msg = "积分账户异常";
					logger.error(msg);
					throw new RuntimeException(msg);
				}
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus()
				.setRollbackOnly();
				throw new RuntimeException(e.getMessage());
			}
		}
		return true;
	}
	
	/**
	 * lzp
	 * @param addType
	 * @return
	 */
	private Integer returnIntegralBycontrol(Integer addType)
	{
		Integer changeIntegeral=0;//变动的积分
		//查询积分控制
		List<TBusiCreditIntegralControl> controlList=tBusiCreditIntegralControlMapper.selectIntegralControlModel();
		for(TBusiCreditIntegralControl obj:controlList)
		{
			if(obj.getControlType()==addType && obj.getIsLock()==0)
			{
				changeIntegeral=Integer.parseInt(obj.getControlValue());
			}
		}
		return changeIntegeral;
	}

	@Override
	public TBusiMember selectMemberByNickName(String nickName) {
		// TODO Auto-generated method stub
		return tBusiMemberMapper.selectMemberByNickName(nickName);
	}

	/**
	 * 转账公共方法  lzp
	 */
	@Transactional(rollbackFor = RuntimeException.class)
	public synchronized boolean transferAccounts(Integer uid, Integer fudouMoney,
			String userName) {
		synchronized (AccountLock.lockMember(uid)) {
			try {
				TBusiMember memberTurnOut = tBusiMemberMapper.findTBusiMemberByUid(uid);
				BigDecimal memberTurnOutMoney=memberTurnOut.getMoney();
				if(memberTurnOutMoney.intValue() <fudouMoney)
				{
					String msg = "用户余额不足";
					logger.error(msg);
					throw new RuntimeException(msg);
				}
				logger.info("插入资金流水【充值】日志start.... 转账开始");
				Integer moneyOut=memberTurnOutMoney.intValue()-fudouMoney;
				boolean insertBolOut=insertAccountLog(memberTurnOut.getUid(), -6, moneyOut, fudouMoney, "转账给用户"+userName+"支出"+fudouMoney+"福豆", memberTurnOut.getUserName(), memberTurnOut.getAutoUser(), memberTurnOut.getuType());
				TBusiMember memberTurnIn=tBusiMemberMapper.selectMemberByUserName(userName.trim());
				Integer moneyIn=memberTurnIn.getMoney().intValue()+fudouMoney;
				boolean insertBolIn=insertAccountLog(memberTurnIn.getUid(), 6, moneyIn, fudouMoney, "用户"+memberTurnOut.getUserName()+"转账,转入"+fudouMoney+"福豆", userName, memberTurnIn.getAutoUser(), memberTurnIn.getuType());
				if(insertBolOut&&insertBolIn)
				{
					memberTurnOut.setMoney(new BigDecimal(moneyOut));
					int result = tBusiMemberMapper.updateByPrimaryKeySelective(memberTurnOut);
					if(result>0)
					{
						memberTurnIn.setMoney(new BigDecimal(moneyIn));
						result=tBusiMemberMapper.updateByPrimaryKeySelective(memberTurnIn);
						if(result>0)
						{
							return true;
						}else
						{
							TransactionAspectSupport.currentTransactionStatus()
							.setRollbackOnly();
							return false;
						}
					}
				}
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus()
				.setRollbackOnly();
				return false;
			}
		}
		return true;
	}
	

	
	
	/**
	 * 日志私有方法
	 * @return
	 */
	private boolean insertAccountLog(Integer uid,int type,Integer money,Integer shMoney,String content,String userName,Integer autoUser,Integer uType)
	{
		TBusiMemberAccountLog accountLog = new TBusiMemberAccountLog();
		accountLog.setUid(uid);
		accountLog.setType(type);//兌换福豆
		accountLog.setUseMoney(new BigDecimal(money));//金额变动后的金额
		accountLog.setMoney(new BigDecimal(shMoney));//操作金额
		accountLog.setContent(content);
		accountLog.setAddTime(YXDate.getTime());
		accountLog.setUserName(userName);
		accountLog.setAutoUser(autoUser);
		accountLog.setuType(uType);
		accountLog.setShardingKey(ShardingMonthUtil.currentShardingMonth());
		int result  =  accountLogMapper.insert(accountLog);
		return result>0;
	}


	public List<Integer> selectGroupIdByRefundment(){
		return reviewMapper.selectGroupIdByRefundment();
	}

	public Integer selectGroupRefundmentCount(Integer groupId){
		return reviewMapper.selectGroupRefundmentCount(groupId);
	}

	@Override
	public TBusiMember selectMemberByOnlyCode(String onlycode) {
		return tBusiMemberMapper.selectMemberByOnlyCode(onlycode);
	}
	

}
